let express = require('express')
let fs = require('fs')
let path = require('path')
let jwt = require('jsonwebtoken')
//创建子路由对象
let userRouter = express.Router()


//分页
userRouter.get( '/list' , (req,res)=>{
    //获取get参数
    var { page,count } = req.query

    //读取users.json文件
    let filepath = path.join( __dirname , '../json/users.json' )
    let arr = fs.readFileSync(filepath)
    arr = arr.toString()?JSON.parse( arr ):[]
    //分页
    let newarr = arr.slice((page-1)*count,page*count)

    res.send({ code:200 , msg:'请求成功！' , list:newarr })
} )

//注册
userRouter.post('/register' , (req,res)=>{
    
  
    var {phone , number , code , name , sort } = req.body

    //读取users.json文件
    let filepath = path.join( __dirname , '../json/users.json' )
    let arr = fs.readFileSync(filepath)
    arr = arr.toString()?JSON.parse( arr ):[]

    //判断用户是否已存在
    let i = arr.findIndex((item)=>{
        return item.phone == phone
    })
    if( i != -1 ){ //用户已存在
        res.send( { code:400,msg:'该手机号已注册,注册失败!' } )
    }else{
        
        arr.push({...req.body,number:1,code:['ceo','se','hr','user'],name:['董事长','项目经理' ,'人力资源' ,'普通员工'],sort:1,time:"2022-10-19 20:56:47",status:'正常'})
        fs.writeFileSync( filepath, JSON.stringify(arr) , 'utf8' )
        res.send({ code:200,msg:'注册成功!' })
    }
})

//登录
userRouter.post( '/login',(req,res)=>{

    let { phone , pass } = req.body

    //读取users.json文件中的用户数据
    var filepath = path.join( __dirname, '../json/users.json' );
    var arr = fs.readFileSync(filepath);
    arr = arr.toString()?JSON.parse( arr ): []

   //做判断
    let i = arr.findIndex((item , index)=>{
        return item.phone == phone  && item.pass == pass
    })
    //客户端的数据是合法的
    if( i != -1){
        let token = jwt.sign( { phone }, '1234' , { algorithm:'HS256',expiresIn:60*5 })

        //登陆成功 
        res.send({ code:200 , msg:'登陆成功！' , userinfo:arr[i],token })
    }else{
        res.send({ code:400,msg:'登陆失败！' })
    }
} )

//导出这个子路由对象
module.exports = userRouter
